package com.gmail.hh.flickrj.sample.android.fragments;


import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.gmail.hh.flickrj.sample.android.FlickrjMainActivity;
import com.gmail.hh.flickrj.sample.android.R;
import com.gmail.hh.flickrj.sample.android.data.DataManagerFlickr;
import com.gmail.hh.flickrj.sample.android.data.PhotoData;
import com.gmail.hh.flickrj.sample.android.data.PhotolistData;
import com.gmail.hh.flickrj.sample.android.data.PhotolistData.IPhotolistZoomChanged;
import com.gmail.hh.flickrj.sample.android.images.LazyAdapterContacts;
import com.gmail.hh.flickrj.sample.android.images.LazyAdapterContacts.IRemoveContactListener;
import com.gmail.hh.flickrj.sample.android.images.LazyAdapterPhotolist;
import com.gmail.hh.flickrj.sample.android.interfaces.IDataReadyListener;
import com.gmail.hh.flickrj.sample.android.interfaces.IPhotoSelectedListener;
import com.gmail.hh.flickrj.sample.android.interfaces.IUserSelectedListener;
import com.googlecode.flickrjandroid.contacts.Contact;
import com.googlecode.flickrjandroid.people.User;


@SuppressLint("NewApi")
public class FragmentContacts extends ListFragment implements
										IDataReadyListener,
										IRemoveContactListener {

	private static final Logger logger = LoggerFactory.getLogger(FlickrjMainActivity.class);
	
	public static final String TAG = "fragment_contacts";
	
	ImageButton btnSearchContacts;
	ImageButton btnAddContacts;
	EditText inputSearchContacts;
	TextView resultContacts;
	
	private Collection<User> mContactsUser;
	private User mUserForContacts;
	private LazyAdapterContacts mAdapterList;
	
	
	// each Activity which uses this Fragment must implement this interface
	private IUserSelectedListener mCallbackUserSelected;
	private Activity mActivity;


	@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
        	mCallbackUserSelected = (IUserSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement IUserSelectedListener");
        }
	}
	

	@Override
	public void onCreate(Bundle arg0) {

		super.onCreate(arg0);
		setRetainInstance(true);
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle data) {
		// Inflate the  layout file.
		View view = inflater.inflate(R.layout.fragment_contacts, null);
		
		this.inputSearchContacts = (EditText) view.findViewById(R.id.inputSearchContacts);	
		this.resultContacts = (TextView) view.findViewById(R.id.resultContacts);		
		this.btnSearchContacts = (ImageButton) view.findViewById(R.id.btnSearchContacts);
		this.btnAddContacts = (ImageButton) view.findViewById(R.id.btnAddContacts);
		return view;
	}

	@Override
	public void onViewCreated(View arg0, Bundle arg1) {
		super.onViewCreated(arg0, arg1);  

	    // search
		this.btnSearchContacts.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				logger.error("Search Contacts: "   );
				performSearch();
			}
		});
	    // add Contact
		this.btnAddContacts.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				logger.error("Add Contacts: "   );
				reloadData(true);
			}
		});

	}
	
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        // reload actual Data from DataManager
		if ( !hidden ) {
			boolean forceRefresh = false;
			if ( mContactsUser==null ) {
				forceRefresh = true;
			}
			this.reloadData(forceRefresh);
	    }
    }
    
    @Override
    public void onDestroy() {
		setListAdapter(null);
        super.onDestroy();
    }
	
    // action, when an item of the list is clicked
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		//call activity method (communication with activity)
		logger.error("Selected Contact: " + position  );
        User user = mAdapterList.getItem(position);
		mCallbackUserSelected.onUserSelected(user);
	}
	

    
    // refresh (call also be invoked by external classes)
    public void reloadData(boolean forceRefresh) {
    	if (forceRefresh)  {
    	    DataManagerFlickr.getInstance().loadContacts(this);
        } else {
    	    onDataReady(true);
        }
    }
	

	// a new/actualized Data-Object is available by DataManager
	@Override
	public void onDataReady(boolean success) {
		if (success) {
			// replace list of existing contacts
			mContactsUser = DataManagerFlickr.getInstance().getContactsUserIncludingLoginUser();
		//	logger.error("Number of Contact: " + mContactsUser.size()  );
			if (mContactsUser!=null ) {
				// set Adapter for List-View
				this.createNewAdapter();
	        }
			// set search-result for searching new contacts
//			btnAddContacts.setVisibility(View.GONE);
			mUserForContacts =  DataManagerFlickr.getInstance().getUserForContacts();
			String resultText = inputSearchContacts.getText().toString() + ": " +
						getResources().getString(R.string.searchNoResultContact);
			if (inputSearchContacts.getText().toString()==null || 
					inputSearchContacts.getText().toString().isEmpty() ) {
				resultText = getResources().getString(R.string.searchEnterUsername) ;
	        }
			if (mUserForContacts!=null ) {
				resultText = mUserForContacts.getUsername() ;
				if (mUserForContacts.getRealName()!=null && !mUserForContacts.getRealName().isEmpty() ) {
					resultText = resultText + " (" + mUserForContacts.getRealName() + ")" ;
					btnAddContacts.setVisibility(View.VISIBLE);
				}
	        }
			resultContacts.setText(resultText);
        }
	}
	

	// set Adapter for List-View
	private void createNewAdapter() {		
		mAdapterList = new LazyAdapterContacts(this, this, getActivity(), mContactsUser );
		setListAdapter(mAdapterList);
	}
	


	// set Adapter for List-View
	private void performSearch() {		
		if (inputSearchContacts.getText()!=null ) {
			String searchUsername = inputSearchContacts.getText().toString();
			if (searchUsername!=null && !searchUsername.isEmpty() ) {
				String resultText = getResources().getString(R.string.searchInProgress);
				btnAddContacts.setEnabled(false);
				resultContacts.setText(resultText);
	    	    DataManagerFlickr.getInstance().findUserForContacts(this, searchUsername);
			}
		}
		
	}

	
	// this event is defined in the listview-adapter 
	@Override
	public void onRemoveContact(int position) {
		logger.error("Selected Contact for Remove: " + position   );
		
	}
	

	

}
